<?php
class BanIp extends CActiveRecord {
    
    public $id;
    public $isForever;
    public $unbanTime;
    public $userId;
    public $ip;
    
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }
    
    public function beforeValidate() {
        if(!parent::beforeValidate()) return false;
        $this->attributes = !empty($_POST[get_class($this)]) ? $_POST[get_class($this)] : array();
        return true;
    }
    
    public function rules() {
        return array(
            array('ip', 'required', 'message' => '{attribute} не может быть пустым'),
            array('ip', 'unique', 'message' => 'этот ip уже есть в списке'),
            array('ip', 'match', 'pattern'=>'/^(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])){3}$/', 'message'=>'не верный формат ip'),
            array('isForever, unbanTime', 'safe'),
            array('unbanTime', 'type', 'type' => 'date', 'message' => 'Не верный формат даты', 'dateFormat' => 'dd.MM.yyyy H:m'),
        );
    }

    public function tableName() {
        return 'banned_ip';
    }
    
    public function beforeSave() {
        if(!parent::beforeSave()) return false;
        $this->userId = Yii::app()->user->getId();
        if(!$this->isForever) {
            if(!empty($this->unbanTime)) {
                $date = explode(' ', $this->unbanTime);
                $dmy = explode('.', $date[0]);
                $hm = explode(':', $date[1]);
                $this->unbanTime = mktime($hm[0], $hm[1], null, $dmy[1], $dmy[0], $dmy[2]);
            } else $this->isForever = 1;
        } else $this->unbanTime = 0;
        return true;
    }
    
    public function afterFind() {
        $this->unbanTime = date('d.m.Y H:i', $this->unbanTime);
    }
    
    public function attributeLabels() {
        return array(
            'ip'=>'ip адрес',
            'isForever'=>'Навсегда',
            'unbanTime'=>'Дата разбана'
        );
    }
}
